<script setup lang="ts">
import type { DataItem } from './data';

import { onMounted, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';

import {
  Button,
  ButtonGroup,
  Dropdown,
  DropdownButton,
  Input,
  Menu,
  Table,
} from 'ant-design-vue';

import { delUserApi, getUserListApi, updateUserInfoApi } from '#/api';

import { columns } from './data';

const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});
const datasource = ref<DataItem[]>([]);
const updateUserInfo = async (key: string) => {
  const target = datasource.value.find((item) => item.key === key)!;
  const data = {
    id: target.key as number,
    username: target.username,
    email: target.email,
    status: target.status,
    type: target.t,
    createTime: target.create_time,
    headerUrl: target.header_url,
  };
  const result = await updateUserInfoApi(data);
  if (result.code === 200) {
    // 更新成功
    // console.log('更新成功');
  } else {
    // 更新失败
    // console.log('更新失败');
  }
};
const edit = (key: string) => {
  const target = datasource.value.find((item) => item.key === key)!;
  editableData[key] = Object.assign({}, target);
};
const cancel = (key: string) => {
  delete editableData[key];
};
const delUser = async (key: string) => {
  const result = await delUserApi(key);
  if (result.code === 200) {
    // 删除成功
    // console.log('删除成功');
  } else {
    // 删除失败
    // console.log('删除失败');
  }
};

const del = (key: string) => {
  const target = datasource.value.find((item) => item.key === key)!;
  const index = datasource.value.indexOf(target);
  if (index) {
    datasource.value.splice(index, 1);
  }
  delUser(key);
  // 删除成功后，删除 editableData 中对应的项
  delete editableData[key];
};
const save = (key: string) => {
  const target = datasource.value.find((item) => item.key === key)!;

  Object.assign(target, editableData[key]);
  // 这里可以添加保存数据的逻辑，比如发送请求到服务器
  updateUserInfo(key);
  delete editableData[key];
};

const onclick = (e: any, key: string, dataIndex: string) => {
  editableData[key]![dataIndex] = e.key;
};

const getuserList = async () => {
  const data = await getUserListApi();
  const userList = data.users;
  userList.forEach((item) => {
    datasource.value.push({
      key: item.id,
      username: item.username,
      email: item.email,
      status: item.status,
      t: item.type,
      create_time: item.createTime,
      header_url: item.headerUrl,
    });
  });
};

onMounted(() => {
  getuserList();
});
</script>
<template>
  <Table :columns :data-source="datasource">
    <template #bodyCell="{ column, text, record }">
      <template
        v-if="
          column.dataIndex &&
          ['username', 'email'].includes(column.dataIndex as string)
        "
      >
        <div>
          <Input
            v-if="editableData[record.key]"
            v-model:value="
              editableData[record.key]![column.dataIndex as string]
            "
          />
          <template v-else>
            <span>{{ text }}</span>
          </template>
        </div>
      </template>
      <template
        v-if="
          column.dataIndex && ['status'].includes(column.dataIndex as string)
        "
      >
        <div>
          <Dropdown v-if="editableData[record.key]">
            <DropdownButton>
              {{
                editableData[record.key]![column.dataIndex as number] === '1'
                  ? '是'
                  : '否'
              }}
            </DropdownButton>
            <template #overlay>
              <Menu
                @click="onclick($event, record.key, column.dataIndex as string)"
              >
                <Menu.Item key="1">
                  <span>是</span>
                </Menu.Item>
                <Menu.Item key="0">
                  <span>否</span>
                </Menu.Item>
              </Menu>
            </template>
          </Dropdown>
          <template v-else>
            <span>{{ text === '1' ? '是' : '否' }}</span>
          </template>
        </div>
      </template>
      <template
        v-if="column.dataIndex && ['t'].includes(column.dataIndex as string)"
      >
        <div>
          <Dropdown v-if="editableData[record.key]">
            <DropdownButton>
              {{
                editableData[record.key]![column.dataIndex as number] === '1'
                  ? '管理员'
                  : '普通用户'
              }}
            </DropdownButton>
            <template #overlay>
              <Menu
                @click="onclick($event, record.key, column.dataIndex as string)"
              >
                <Menu.Item key="1">
                  <span>管理员</span>
                </Menu.Item>
                <Menu.Item key="0">
                  <span>普通用户</span>
                </Menu.Item>
              </Menu>
            </template>
          </Dropdown>
          <template v-else>
            <span>{{ text === '1' ? '管理员' : '普通用户' }}</span>
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div>
          <div v-if="editableData[record.key]">
            <ButtonGroup>
              <Button @click="save(record.key)">保存</Button>
              <Button @click="del(record.key)">删除</Button>
              <Button @click="cancel(record.key)">取消</Button>
            </ButtonGroup>
          </div>
          <div v-else>
            <Button @click="edit(record.key)">编辑</Button>
          </div>
        </div>
      </template>
    </template>
  </Table>
</template>

<style scoped></style>
